<template>
  <div class="popularize-mark">
    <!-- 推广标识选择 -->
    <div class="mark-select popular-box">
      <div class="cascader-flex-box">
        <!-- 推广标识选择 -->
        <template :key="index" v-for="(optionItem, index) in popuMarkOptions">
          <div v-if="optionItem[0] && optionItem[0].nodes" :key="index" class="cascader-cls">
            <label class="popular-cascader-label">{{optionItem[0].text}} :</label>
            <el-cascader
              :options="optionItem[0].nodes"
              :props="{ checkStrictly: false, value: 'key', label: 'text', children: 'nodes', leaf: 'leaf' }"
              @change="handleCascaderChange($event, 'mark_' + index)"
              clearable>
            </el-cascader>
          </div>
        </template>
      </div>

      <!-- date-picker -->
      <div class="date-picker-box">
        <label class="popular-cascader-label">日期 :</label>
        <el-date-picker
          v-model="pickerDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          :disabled-date="pickerOptions.disabledDate"
          :shortcuts="pickerOptions.shortcuts">
        </el-date-picker>
      </div>

      <!-- 推广标识生成按钮 -->
      <div class="mark-select-add popular-btn">
        <p>
          <el-button type="primary" :disabled="!bIsSelect" :plain="!bIsSelect" @click="click2Generate">生成</el-button>
        </p>
      </div>
    </div>

    <!-- 推广标识生成列表 -->
    <div class="popularize-list" v-if="markLists && markLists.length > 0">
      <!-- table -->
      <el-table
        :data="markLists"
        style="width: 100%">
        <el-table-column prop="id" label="id" width="100"></el-table-column>
        <el-table-column prop="url" label="url">
          <template #default="scope">
            <el-tooltip content="点击复制" placement="top" effect="light">
              <span class="clipboard-cls" @click.stop="clipboardCopy(scope.row.url)">{{ scope.row.url }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="fr" label="fr"></el-table-column>
        <el-table-column prop="fr_zh" label="fr_zh"></el-table-column>
        <el-table-column prop="qrcode_url" label="qrcode_url"></el-table-column>
        <el-table-column prop="add_time" label="add_time"></el-table-column>
      </el-table>
    </div>

    <!-- pagination -->
    <p class="popular-pag" v-if="markLists && markLists.length > 0">
      <el-pagination
        v-if="totalPage"
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :page-count="totalPage"
        :current-page="popuCurPage"
        @current-change="handleCurrentChange">
      </el-pagination>
    </p>

    <!-- NoData -->
    <NoData style="margin-top: 40px;" v-if="!markLists || markLists.length <= 0"></NoData>
  </div>
</template>

<script>
  import NoData from '@/views/child/admin/adminData/NoData.vue'
  import { mapState, mapActions } from 'vuex'
  import { copyUtils } from '@/views/js/copy-utils'
  import { reactive } from 'vue'

  export default {
    mixins: [copyUtils],
    setup () {
      const state =  reactive({
        dictionaryTree: [],
        pickerDate: null,
      })
      const state_ = {
        // mark select
        mapSelectMarks: {},  // Map: 记录选择项
        bIsSelect: false,  // 是否有选择项
        // popuMarkOptions: [
        //   [
        //     {
        //       value: 'A',
        //       label: '推广渠道',
        //       children: [],
        //     },
        //   ]
        // ],

        // date picker
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [
            {
              text: '今天',
              value: new Date()
            },
            {
              text: '昨天',
              value: () => {
                const date = new Date()
                date.setTime(date.getTime() - 3600 * 1000 * 24)
                return date
              }
            },
            {
              text: '一周前',
              value: () => {
                const date = new Date()
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
                return date
              }
            }
          ]
        },
        // mark list
        popuCurPage: 1,
        pageSize: 20,
      }
      _.merge(state, state_)
      return state
    },
    props: ['site_id'],
    components: {
      NoData,
    },
    computed: {
      ...mapState({
        markLists: state => state.user.myPopularize.popularMarkData.list,
        totalPage: state => state.user.myPopularize.popularMarkData.totalPage || 0,
      }),
      popuMarkOptions() {
        // 匹配 el-cascader elementUi 数据格式
        return this.dictionaryTree && this.dictionaryTree
          // .filter((node) => {
          //   // 过滤不展示的 node
          //   const MAP_TREE = ['A', 'B', 'C', 'D', 'E'];
          //   return MAP_TREE.indexOf(node.key) > -1;
          // })
          .map((node) => {
            return [node];
          })
      },
    },
    beforeMount() {
      const that = this;
      // post 4 dictionarytree
      this.getDictionaryTree({
        site_id: this.site_id,
        callback: (data) => {
          that.dictionaryTree = that.deepLook4Leaf(data, 'nodes');
        },
      });

      // 初始化获取 promtLists
      this.popuCurPage = 1;
      this.getPromtLists({
        site_id: this.site_id,
        page: this.popuCurPage,
        pageSize: this.pageSize,
      });
    },
    mounted() {},
    methods: {
      ...mapActions({
        getPromtLists: 'user/getPromtLists',
        addPromt: 'user/addPromt',
        getDictionaryTree: 'user/getDictionaryTree',
        clearPromtLists: 'user/clearPromtLists',
      }),
      handleCurrentChange(val) {
        // 根据 页数 获取 promtList
        this.popuCurPage = val;
        this.getPromtLists({
          site_id: this.site_id,
          page: this.popuCurPage,
          pageSize: this.pageSize,
        });
      },
      handleCascaderChange(item, index) {
        // mapSelectMarks  Map: 记录选择项
        if(item.length > 0) {
          this.mapSelectMarks[index] = item[item.length - 1];
        }
        else {
          delete this.mapSelectMarks[index];
        }

        // bIsSelect  是否有选择项
        this.bIsSelect = Object.keys(this.mapSelectMarks).length > 0;
      },
      click2Generate() {
        const that = this;

        // if mapSelectMarks ?
        const totalSelectMarkKeys = this.mapSelectMarks && Object.keys(this.mapSelectMarks);
        if(!totalSelectMarkKeys || totalSelectMarkKeys.length <= 0) return;

        // 拼接 strMarks
        let strMarks = '';
        totalSelectMarkKeys.forEach((key) => {
          const strMarksByKey = that.mapSelectMarks[key];
          strMarks += strMarks.length > 0 ? ( '_' + strMarksByKey ) : strMarksByKey;
        });

        // 拼接 日期
        const newPickerDate = this.pickerDate && this.pickerDate != "" ? this.pickerDate : this.getNowDate();
        strMarks += '_T' + newPickerDate.split('-').join('');

        // post
        this.addPromt({
          site_id: this.site_id,
          stfr: strMarks,
          callback: () => {
            // 重新获取 promtList
            that.popuCurPage = 1;
            that.getPromtLists({
              site_id: that.site_id,
              page: that.popuCurPage,
              pageSize: that.pageSize,
            });
          },
        });
      },
      deepLook4Leaf(tree, nodeKey) {
        // 寻找 tree 的 leaf 节点， 并设置标识位 leaf
        if(Object.prototype.toString.call(tree) !== "[object Array]" || tree.length <= 0) return false;

        const key = Object.prototype.toString.call(nodeKey) === "[object String]" && nodeKey != ""
          ? nodeKey : 'children';

        for(let i = 0; i < tree.length; i++) {
          tree[i][key] = this.deepLook4Leaf(tree[i][key], nodeKey);
          if(!tree[i][key]) {
            tree[i].leaf = 'leaf';
          }
        }

        return tree;
      },
      getNowDate() {
        // 返回 当前日期， 格式为： ‘2020-01-10’
        let y = new Date().getFullYear();
        let month = new Date().getMonth() + 1;
        month = month >= 10 ? month : ( '0' + month );
        let day = new Date().getDate();
        day = day >= 10 ? day : ( '0' + day );
        return y + '-' + month + '-' + day;
      },
    },
    beforeUnmount() {
      this.clearPromtLists();
    },
  }
</script>

<style lang="scss" scope>
  .popular-box {
    min-width: 460px;
    padding: 20px 10px;
    margin: 20px 20px;
    background-color: #fff;
    box-shadow: 5px 8px 12px #ebedf0;
  }

  .popular-btn {
    padding: 10px 35px;
    margin-top: 30px;
  }

  .popular-pag {
    margin-top: 45px;
    margin-bottom: 40px;
    text-align: center;
  }

  .popularize-list {
    // padding-bottom: 20px;
    margin: 20px 20px;
    box-shadow: 5px 8px 12px #ebedf0;

    .el-table{
      font-size:12px;

      .el-table__header {
        tr {
          background-color: #e4e7eb;
        }

        th {
          font-size: 14px;
          background-color: #e4e7eb;
          color: #43475c;
          font-weight: normal;
        }
      }

      .el-table__header, .el-table__body {
        tr {
          position: relative;

          td:nth-child(1) , th:nth-child(1) {
            div {
              text-align: center;
            }
          }
        }
      }
    }
  }

  .clipboard-cls:hover {
    cursor: pointer;
    color: #409EFF;
  }

  .cascader-flex-box {
    display: flex;
    flex-direction: column-reverse;
  }

  .cascader-cls {
    margin-bottom: 10px;

    .el-cascader {
      min-width: 400px;
      margin-left: 20px;
    }
  }

  .popular-cascader-label {
    display: inline-block;
    font-size: 14px;
    font-weight: bold;
    color: #909399;
    min-width: 140px;
    // margin-right: 20px;
    text-align: right;
  }

  .date-picker-box {
    .el-date-editor {
      min-width: 400px;
      margin-left: 20px;
    }
  }
  .el-input__prefix-inner{
    align-items: center;
  }
</style>
